<template>
  <div class="dialog">
    <el-dialog :title="'吊水估产记录' + titleText" :visible.sync="showDialog" width="45%" top="0" :close-on-click-modal="false"
      @close="cancel">
      <el-form ref="ruleForm" label-position="left" :model="formData" :rules="rules" class="el-form">
        <!-- <el-form-item label="鱼塘名称:" prop="fishPondId" class="w50p">
          <el-select filterable clearable v-model="formData.fishPondId" filterable clearable @change="queryBatch">
            <el-option v-for="(item, index) in pondList" :key="index" :label="item.pondName" :value="item.fishPondId" />
          </el-select>
        </el-form-item> -->
        <el-form-item label="批次编号:" prop="productionBatchId" class="w50p">
          <el-select filterable clearable v-model="formData.productionBatchId" @change="batchChange">
            <el-option v-for="(item, index) in batchList" :key="index"
              :label="`${item.mnecode}_${item.varietyName}`"
              :value="item.productionBatchId" />
          </el-select>
        </el-form-item>
        <el-form-item label="估产百分比:" prop="rate" class="w50p">
          <el-input v-model="formData.rate" disabled clearable placeholder="请先选择批次" />
        </el-form-item>
        <el-form-item label="系统计算重量:" class="w50p">
          <el-input v-model="formData.weightRange" disabled clearable placeholder="请先选择批次">
            <template slot="append">斤</template>
          </el-input>
        </el-form-item>
        <el-form-item label="估产重量:" prop="predictWeight" class="w50p">
          <el-input v-model="formData.predictWeight" clearable type="number" min="0"
            @change="() => { formData.predictWeight < 0 ? formData.predictWeight = 0 : '' }" placeholder="请输入估产重量">
            <template slot="append">斤</template>
          </el-input>
        </el-form-item>
        <el-form-item label="估产人:" class="w50p" prop="staffId">
          <el-select filterable clearable disabled v-model="formData.staffId" @change="staffChange">
            <el-option v-for="(item, index) in staffList" :key="index" :label="item.staffName" :value="item.staffId" />
          </el-select>
        </el-form-item>
        <el-form-item label="估产日期:" class="w50p" prop="predictDate">
          <el-date-picker v-model="formData.predictDate" type="datetime" placeholder="选择日期"
            value-format="yyyy-MM-dd HH:mm:ss" clearable :picker-options="pickerOptions" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button class="cancelbtn" @click="cancel()">取 消</el-button>
        <el-button type="primary" class="savebtn" @click="save('ruleForm')">保 存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>

import InPondEstimationHandingApi from "@/api/in-pond-estimation/in-pond-estimation-handing"
import BatchMangeApi from "@/api/batch-mange"
import { dialogMixin } from "@/utils/dialogMixin";
let maxTime = null
export default {
  name: '',
  components: {},
  mixins: [dialogMixin],
  props: {
    // 弹框名称
    titleText: {
      type: String,
      default: ""
    },
    nowChanceStau: {
      type: String,
      default: ""
    },
    show: {
      type: Boolean,
      default: false
    },
    editObject: {
      type: [Object],
      default: () => {
        return {}
      }
    },
    staffList: {
      type: [Array],
      default: () => {
        return []
      }
    },
    pondList: {
      type: [Array],
      default: () => {
        return []
      }
    },
  },
  data () {
    let checkInt = (rule, value, callback) => {
      if (value) {
        if (Number(value) && value % 1 === 0) {
          callback();
        } else {
          return callback(new Error("请输入整数！"));
        }
      }
    };
    return {
      pickerOptions: {
        disabledDate (time) {
          return time.getTime() < new Date(new Date(maxTime).getTime(new Date(maxTime))) || time.getTime() > new Date().getTime();
        },

        shortcuts: [{
          text: '今天',
          onClick (picker) {
            picker.$emit('pick', new Date());
          }
        }, {
          text: '昨天',
          onClick (picker) {
            const date = new Date();
            date.setTime(date.getTime() - 3600 * 1000 * 24);
            if (maxTime < date.getTime() - 3600 * 1000 * 24) {
              picker.$emit('pick', date);
            } else {
              picker.$emit('pick', maxTime);
            }
          }
        }, {
          text: '一周前',
          onClick (picker) {
            const date = new Date();
            date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
            if (maxTime < date.getTime() - 3600 * 1000 * 24 * 7) {
              picker.$emit('pick', date);
            } else {
              picker.$emit('pick', maxTime);
            }
          }
        }],
      },
      rules: {
        productionBatchId: [
          { required: true, message: "请选择批次", trigger: ["change", "blur"] }
        ],
        fishPondId: [
          { required: true, message: "请选择鱼塘", trigger: ["change", "blur"] }
        ],
        predictWeight: [
          { required: true, message: "请输入估产重量", trigger: ["change", "blur"] }
        ],
        staffId: [
          { required: true, message: "请输入估产人", trigger: ["change", "blur"] }
        ],
      },
      formData: {},
      batchList: [],//批次
      showDialog: this.show
    };
  },
  computed: {
  },
  watch: {
    show (v) {
      maxTime = null
      this.showDialog = v;
    },
    nowChanceStau (v) {
      if (v === 'add') {
        this.$nextTick(() => {
          let staffName = sessionStorage.getItem('staffName')
          let staffId = Number(sessionStorage.getItem('staffId'))
          let userList = this.staffList.filter(item => {
            return Number(item.staffId) === Number(staffId)
          })
          this.formData = {
            staffName: userList.length == 0 ? this.staffList[0].staffName : staffName,
            staffId: userList.length == 0 ? this.staffList[0].staffId : Number(staffId),
            samplingDateTime: this.getNowTime(),
          }
          this.$set(this.formData, 'predictDate', this.formatDateTimeMHS(new Date()))
          this.$refs['ruleForm'].resetFields()
        })
      }
      if (v === 'edit') {
        this.formData = this.editObject
        this.formData.staffId = Number(this.formData.staffId)
        this.batchChange(this.formData.productionBatchId)
      }
    }
  },
  created () {
    maxTime = null
  },
  mounted () {
    this.queryBatch()
  },
  methods: {
    staffChange (e) {
      this.staffList.find((item) => {
        if (item.staffId === e) {
          this.formData.staffName = item.staffName;
          return true;
        }
      })
    },
    batchChange (e) {
      maxTime = ''
      this.batchList.find((item) => {
        if (item.productionBatchId === e) {
          this.formData.fishPondId = item.fishPondId;
          maxTime = new Date(item.buildDateTime)
          // this.formData.predictDate = this.formatDateTimeMHS(maxTime)
          return true;
        }
      })
      if (e) {
        InPondEstimationHandingApi.generateHangingBreedPredictYield({ productionBatchId: e }).then(res => {
          if (res.success) {
            this.$set(this.formData, 'minRate', res.data.minRate)
            this.$set(this.formData, 'maxRate', res.data.maxRate)
            this.$set(this.formData, 'rate', res.data.maxRate + '% ~ ' + res.data.minRate + '%')
            this.$set(this.formData, 'maxWeight', res.data.maxWeight)
            this.$set(this.formData, 'minWeight', res.data.minWeight)
            this.$set(this.formData, 'weightRange', res.data.minWeight + ' ~ ' + res.data.maxWeight)
            this.$set(this.formData, 'predictYieldConfigId', res.data.predictYieldConfigId)
          } else if (res.errCode === 200) {
            this.$message.warning(res.message);
          }
        })
      }
    },
    queryBatch (e) {
      // this.formData.productionBatchId = undefined;
      this.$set(this.formData, 'productionBatchId', undefined)
      BatchMangeApi.queryByCondition({ breedTypeNo: 'HANGING_BREED' }).then(res => {
        this.batchList = res.data;
        this.formData.productionBatchId = null
      })
    },
    save (formData) {
      this.formData.overdueFlag = false
      if (this.formData.workTime) {
        this.formData.workBeginTime = this.formData.workTime[0]
        this.formData.workEndTime = this.formData.workTime[1]
      }
      this.$refs[formData].validate(valid => {
        if (valid) {
          // 修改
          if (this.nowChanceStau === "edit") {
            InPondEstimationHandingApi.edit(this.formData).then(res => {
              if (res.success === true) {
                if (parseFloat(res.data.estimateDensity) > parseFloat(res.data.density)) {
                  this.$alert('当前实际养殖密度大于标准养殖密度', '提示', {
                    confirmButtonText: '确定', type: 'warning',
                    callback: action => {
                      this.$message.success("修改成功");
                      this.close()
                    }
                  });
                } else {
                  this.$message.success("修改成功");
                  this.close()
                }
              } else {
                this.$message.error(res.message);
              }
            });
          } // 添加
          else if (this.nowChanceStau === "add") {
            InPondEstimationHandingApi.add(this.formData).then(res => {
              console.log('添加的res', res);
              if (res.success === true) {
                if (parseFloat(res.data.estimateDensity) > parseFloat(res.data.density)) {
                  this.$alert('当前实际养殖密度大于标准养殖密度', '提示', {
                    confirmButtonText: '确定', type: 'warning',
                    callback: action => {
                      this.$message.success("添加成功");
                      this.close()
                    }
                  });
                } else {
                  this.$message.success("添加成功");
                  this.close()
                }
              } else {
                this.$message.error(res.message);
              }
            });
          }
        } else {
          return false;
        }
      });
    },
    close () {
      this.$emit("closeDialog");
    },
    cancel () {
      this.$emit("cancelDialog");
    }
  }
};
</script>

<style lang="scss" scoped></style>